<?php
namespace App\Libs\Log;
/**
 * 日志类
 * 高级别日志会写入低级别的日志文件中
 */
class Logger
{
    static $levels = array(
        'debug' => 0,
        'info' => 1,
        'warning' => 2,
        'error' => 3,
    );
    static $sysLogs = array('');

    public static function info($category, $msg) {
        self::log($category, $msg, __FUNCTION__);
    }

    public static function error($category, $msg) {
        self::log($category, $msg, __FUNCTION__);
    }

    public static function warning($category, $msg) {
        self::log($category, $msg, __FUNCTION__);
    }

    public static function debug($category, $msg) {
        self::log($category, $msg, __FUNCTION__);
    }

    public static function log($category, $msg, $level) {
        foreach (self::$levels as $l => $v) {
            // 待写入日志级别高于当前级别，则写入当前级别的日志文件中
            if (self::$levels[$level] >= $v) {
                $logger = self::getLogger($category, $l);
                if ( ! empty($logger)) {
                    call_user_func_array(array($logger, $level), array($msg));
                }
            }
        }
    }

    public static function getLogger($category, $level) {
        $config = \App\Libs\Base\Config::instance()->log;
        if (self::$levels[$level] < self::$levels[$config['level']]) {
            return NULL;
        }
        $category = strtolower($category);
        $level = strtoupper($level);
        $key = $category . ':' . $level;
        if (isset(self::$sysLogs[$key])) {
            return self::$sysLogs[$key];
        }
        $file = $config['dir'] . DIRECTORY_SEPARATOR . $config['prefix'] . $category . '.' . $level . '.' . date('Ymd');
        $logger = new \Phalcon\Logger\Adapter\File($file);
        $formater = new \Phalcon\Logger\Formatter\Line('[%date%] [%type%] %message%', 'Y-m-d H:i:s');
        $logger->setFormatter($formater);
        self::$sysLogs[$key] = $logger;
        return $logger;
    }
}
